package com.yanqu.road.dao.impl.zhaoshang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.zhaoshang.ZsProject;
import com.yanqu.road.entity.zhaoshang.ZsProjectSeat;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ZsProjectDaoImpl extends TempDataObjectDao<ZsProject> {

    public long getMaxProjectId() {
        String sql = "select ifnull(max(projectId),0) as maxId from t_c_zs_project";
        ResultSet rs = null;
        CallableStatement call = null;
        long maxId = 0L;
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                maxId = rs.getLong("maxId");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return maxId;
    }

    @Override
    protected boolean addData(ZsProject data) {
        PreparedStatement call = null;
        String sql = "insert into t_c_zs_project(projectId, serverId, openUserId, templateId, duration, openTime, sendReward, finishType, stateVal, openUser, seatUserMap, seatMap," +
                "titleAddition, addition, decorationOverTime, baseReward) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getProjectId());
            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getOpenUserId());
            call.setInt(i++, data.getTemplateId());
            call.setInt(i++, data.getDuration());
            call.setInt(i++, data.getOpenTime());
            call.setBoolean(i++, data.isSendReward());
            call.setInt(i++, data.getFinishType());
            call.setInt(i++, data.getStateVal());
            call.setString(i++, data.getOpenUserJsonStr());
            call.setString(i++, JSON.toJSONString(data.getSeatUserMap(), SerializerFeature.DisableCircularReferenceDetect));
            call.setString(i++, JSON.toJSONString(data.getSeatMap()));
            call.setInt(i++, data.getTitleAddition());
            call.setInt(i++, data.getAddition());
            call.setLong(i++, data.getDecorationOverTime());
            call.setString(i++, data.getBaseReward());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(ZsProject data) {
        PreparedStatement call = null;
        String sql = "update t_c_zs_project set serverId=?, openUserId=?, templateId=?, duration=?, openTime=?, sendReward=?, finishType=?, stateVal=?, openUser=?, seatUserMap=?, seatMap=?," +
                "titleAddition=?, addition=?, decorationOverTime=?, baseReward=? where projectId=?";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;

            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getOpenUserId());
            call.setInt(i++, data.getTemplateId());
            call.setInt(i++, data.getDuration());
            call.setInt(i++, data.getOpenTime());
            call.setBoolean(i++, data.isSendReward());
            call.setInt(i++, data.getFinishType());
            call.setInt(i++, data.getStateVal());
            call.setString(i++, data.getOpenUserJsonStr());
            call.setString(i++, JSON.toJSONString(data.getSeatUserMap(), SerializerFeature.DisableCircularReferenceDetect));
            call.setString(i++, JSON.toJSONString(data.getSeatMap()));
            call.setInt(i++, data.getTitleAddition());
            call.setInt(i++, data.getAddition());
            call.setLong(i++, data.getDecorationOverTime());
            call.setString(i++, data.getBaseReward());
            call.setLong(i++, data.getProjectId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected ZsProject parseData(ResultSet rs) throws SQLException {
        ZsProject data = new ZsProject();
        String baseUserInfoStr = rs.getString("openUser");
        if(!StringUtils.isNullOrEmpty(baseUserInfoStr)){
            UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
            if(null != userBaseInfo) {
                data.setOpenUser(userBaseInfo);
            }
        }
        data.setSendReward(rs.getBoolean("sendReward"));
        data.setFinishType(rs.getInt("finishType"));
        data.setStateVal(rs.getInt("stateVal"));
        data.setTitleAddition(rs.getInt("titleAddition"));
        data.setAddition(rs.getInt("addition"));
        data.setDecorationOverTime(rs.getLong("decorationOverTime"));
        data.setProjectId(rs.getLong("projectId"));
        data.setServerId(rs.getLong("serverId"));
        data.setOpenUserId(rs.getLong("openUserId"));
        data.setDuration(rs.getInt("duration"));
        data.setTemplateId(rs.getInt("templateId"));
        data.setOpenTime(rs.getInt("openTime"));
        String seatMapStr = rs.getString("seatMap");
        if (!StringUtils.isNullOrEmpty(seatMapStr)) {
            data.setSeatMap(JSON.parseObject(seatMapStr, new TypeReference<ConcurrentHashMap<Integer, ZsProjectSeat>>() {
            }));
        }
        String seatUserMapStr = rs.getString("seatUserMap");
        if (!StringUtils.isNullOrEmpty(seatUserMapStr)) {
            try {
                data.setSeatUserMap(JSON.parseObject(seatUserMapStr, new TypeReference<ConcurrentHashMap<Integer, UserBaseInfo>>() {
                }));
            }catch (Exception e){
                logger.error("seatUserMap parse {} error", seatUserMapStr, e);
            }
        }
        data.setBaseReward(rs.getString("baseReward"));
        return data;
    }

    public Map<Long, Map<Long, ZsProject>> getZsAllProjectMap(int beginTime) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, Map<Long, ZsProject>> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_c_zs_project where projectid > (select projectid from t_c_zs_project where openTime < ? order by projectId desc LIMIT 1)";
        try {
            int i=1;
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(i++, beginTime);
            rs = call.executeQuery();
            while (rs.next()) {
                ZsProject data = parse(rs);
                if(!dataMap.containsKey(data.getServerId())){
                    dataMap.put(data.getServerId(), new ConcurrentHashMap<>());
                }
                dataMap.get(data.getServerId()).put(data.getProjectId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;


    }
}
